<?php

namespace App\Library\Traits;

use Exception;
use PhpAmqpLib\Channel\AMQPChannel;
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Exchange\AMQPExchangeType;
use PhpAmqpLib\Wire\AMQPTable;

trait RabbitMQTrait
{
    /**
     * Desc:
     * @param array $mq
     * @return AMQPStreamConnection
     * @throws Exception
     */
    public static function connection(array $mq): AMQPStreamConnection
    {
        return new AMQPStreamConnection(
            $mq['host'],
            $mq['port'],
            $mq['user'],
            $mq['password'],
            $mq['vhost']
        );
    }

    /**
     * Desc:
     * @param AMQPStreamConnection $connection
     * @param array $mq
     * @return AMQPChannel
     */
    public static function channel(AMQPStreamConnection $connection, array $mq): AMQPChannel
    {
        //在已连接基础上建立生产者与mq之间的通道
        $channel = $connection->channel();
        //声明初始化交换机
        //参数：交换机名，路由类型，是否检测同名队列，是否开启队列持久化，通道关闭后是否删除队列
        $channel->exchange_declare(
            $mq['exchange'],
            $mq['type'],
            false,
            true,
            false,
            false,
            false,
            new AMQPTable([
                'x-delayed-type' => AMQPExchangeType::FANOUT
            ])
        );
        $channel->queue_declare(
            $mq['queue'],
            false,
            true,
            false,
            false,
            false,
            new AMQPTable([
                'x-dead-letter-exchange' => 'delayed'
            ])
        );

        //将队列与某个交换机进行绑定，并使用路由关键字
        //参数：队列名，交换机名，路由键名
        $channel->queue_bind(
            $mq['queue'],
            $mq['exchange'],
            $mq['routingKey']
        );
        return $channel;
    }
}
